
import os
from datetime import datetime
from typing import List
from fastapi import UploadFile, File

from config import project_root
from tables.user import UserModel
from tables.file import Files

async def upload(files: List[UploadFile] = File(...), faq_id: int=0, current_user: UserModel = None):
    """
    文件上传接口，支持单文件和多文件上传
    """
    for file in files:
        user_upload_dir = os.path.join(project_root, "data", "user_files", current_user.username, str(faq_id))
        if not os.path.exists(user_upload_dir):
            os.makedirs(user_upload_dir)

        file_path = os.path.join(user_upload_dir, file.filename)

        # 保存文件
        content = await file.read()
        with open(file_path, "wb") as f:
            f.write(content)

        now = datetime.now()
        # 格式化为 yyyy-MM-dd HH:mm:ss
        formatted_date_time = now.strftime('%Y-%m-%d %H:%M:%S')
        is_chunk: bool = False
        # 保存文件信息到数据库
        file_res = Files.insert_new_file(current_user.id, os.path.basename(file_path), str(faq_id), file_path,formatted_date_time,is_chunk,3,0)
        return  file_res
